package com.wyw.learning.thread.atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.stream.IntStream;

/**
 * 演示LongAccumulator的用法
 *
 *  Accumulator和Adder非常相似，Accumulator就是一个更加通用版本的Adder
 *  适合大量计算的场景，如果不需要大量计算，for循环就可以解决问题（顺序不可以有要求）
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
public class LongAccumulatorDemo {
    public static void main(String[] args) {
//        LongAccumulator accumulator = new
//                LongAccumulator((x,y) -> x+y, 0);//x初始值，y后来值,identity起始值，可以自修改identity起始值或者.accumulate(7)
//        accumulator.accumulate(7);
//        System.out.println(accumulator.getThenReset());

        //有优雅写法
//        LongAccumulator accumulator = new LongAccumulator((x, y) -> x + y, 0);
        LongAccumulator accumulator = new LongAccumulator((x, y) -> 2 + x * y, 1);//可以自定义方法
        ExecutorService executor = Executors.newFixedThreadPool(8);
        IntStream.range(1, 10).forEach(i -> executor.submit(() -> accumulator.accumulate(i)));

        executor.shutdown();
        while (!executor.isTerminated()) {

        }
        System.out.println(accumulator.getThenReset());
    }
}
